package com.example.demo12.myservlet;

import com.example.demo12.entity.CartItem;
import com.example.demo12.entity.Product;
import com.example.demo12.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    private ProductService productService;

    @Override
    public void init() throws ServletException {
        super.init();
        productService = new ProductService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");

        if (cart == null) {
            cart = new HashMap<>();
            session.setAttribute("cart", cart);
        }

        if (action != null) {
            switch (action) {
                case "add":
                    addItemToCart(request, cart);
                    break;
                case "remove":
                    removeItemFromCart(request, cart);
                    break;
                case "clear":
                    clearCart(cart);
                    break;
                case "update":
                    updateItemQuantity(request, cart);
                    break;
                case "checkout":
                    handleCheckout(request, response, session, cart);
                    return;
                default:
                    break;
            }
        }

        request.setAttribute("cart", cart);
        request.getRequestDispatcher("/cart.jsp").forward(request, response);
    }

    private void addItemToCart(HttpServletRequest request, Map<Integer, CartItem> cart) {
        int productId = Integer.parseInt(request.getParameter("id"));
        int stock = Integer.parseInt(request.getParameter("stock"));
        Product product = productService.getAllProducts().stream()
                .filter(p -> p.getId() == productId).findFirst().orElse(null);

        if (product != null) {
            cart.put(productId, new CartItem(product, stock));
        }
    }

    private void removeItemFromCart(HttpServletRequest request, Map<Integer, CartItem> cart) {
        int productId = Integer.parseInt(request.getParameter("id"));
        cart.remove(productId);
    }

    private void clearCart(Map<Integer, CartItem> cart) {
        cart.clear();
    }

    private void updateItemQuantity(HttpServletRequest request, Map<Integer, CartItem> cart) {
        int productId = Integer.parseInt(request.getParameter("id"));
        int newStock = Integer.parseInt(request.getParameter("stock"));

        if (cart.containsKey(productId)) {
            cart.get(productId).setStock(newStock);
        }
    }

    private void handleCheckout(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<Integer, CartItem> cart) throws ServletException, IOException {
        // 执行结算逻辑
        // 处理完后，清空购物车并重定向到成功页面
        cart.clear();
        session.setAttribute("cart", cart);
        response.sendRedirect(request.getContextPath() + "/checkoutSuccess.jsp");
    }
}